import Heart from "@/components/Heart";
import { ImageSlider } from "@/components/slidePager";
import AntDesign from "@expo/vector-icons/AntDesign";
import Entypo from "@expo/vector-icons/Entypo";
import EvilIcons from "@expo/vector-icons/EvilIcons";
import dayjs from "dayjs";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useEffect, useState } from "react";
import {
  Dimensions,
  Image,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
export default function Index() {
  const router = useRouter();
  const [height, setHeight] = useState<number>(300);
  const { width: SCREEN_WIDTH } = Dimensions.get("window");
  const userInfo = {
    avatar:
      "https://gips1.baidu.com/it/u=705524004,2611014536&fm=3074&app=3074&f=PNG?w=2048&h=2048",
  };
  const detail = {
    avatarUrl:
      "https://img2.baidu.com/it/u=902203086,3868774028&fm=253&app=138&f=JPEG?w=500&h=500",
    userName: "张三",
    images: [
      "https://img0.baidu.com/it/u=1168912228,741609775&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800",
      "https://gips3.baidu.com/it/u=1014935733,598223672&fm=3074&app=3074&f=PNG?w=1440&h=2560",
      "https://img0.baidu.com/it/u=2779316202,721068756&fm=253&app=120&f=JPEG?w=1422&h=800",
    ],
    title: "让我抱抱，一起温暖，真的好治愈",
    desc: "家里鸡蛋不知道怎么吃的，可以去试试这个火腿肠炒蛋，\n我妈说居然这么好吃。\n香辣过瘾真的忒下饭了，做法鸡蛋，你们也去安排起来。",
    tag: ["每秒都值得记录", "治愈系", "治愈猫咪"],
    dateTime: "2023-02-27 12:20",
    location: "广东",
    favoriteCount: 1098,
    collectionCount: 208,
    isFavorite: false,
    isCollection: false,
    comments: [
      {
        userName: "胖胖胖",
        avatarUrl:
          "https://img0.baidu.com/it/u=2875122849,1736556673&fm=253&app=138&f=JPEG?w=500&h=500",
        message:
          "果断关注，这个博主做的菜真实色香味俱全。每天跟着学做菜，我要做大厨了，啊哈哈～",
        dateTime: "2023-02-28 07:23",
        location: "成都",
        favoriteCount: 45,
        isFavorite: false,
        children: [
          {
            userName: "小飞飞爱猫咪",
            avatarUrl:
              "https://img2.baidu.com/it/u=1922178401,3519789815&fm=253&app=138&f=JPEG?w=500&h=500",
            message: "安排起来，这个做法很简单的哦。",
            dateTime: "2023-02-28 13:23",
            location: "广东",
            favoriteCount: 1,
            isFavorite: false,
          },
        ],
      },
      {
        userName: "左半",
        avatarUrl:
          "https://img2.baidu.com/it/u=3118961545,1128223138&fm=253&app=138&f=JPEG?w=500&h=500",
        message: "看着真有食欲",
        dateTime: "2023-02-28 09:09",
        location: "福建",
        favoriteCount: 2,
        isFavorite: false,
        children: undefined,
      },
    ],
  };
  useEffect(() => {
    if (!detail?.images) {
      return;
    }
    const firstImg = detail?.images[0];
    Image.getSize(firstImg, (width: number, height: number) => {
      const showHeight = (SCREEN_WIDTH * height) / width;
      setHeight(showHeight);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const params = useLocalSearchParams();
  const { id } = params;
  // 此处省略访问接口获取文章详情
  // console.log(id);
  const renderImages = () => {
    const { images } = detail;
    if (!images?.length) {
      return null;
    }
    const data: any[] = detail.images.map((i) => {
      return { img: i };
    });
    return (
      <View style={{ paddingBottom: 30 }}>
        <ImageSlider
          data={data}
          autoPlay={false}
          closeIconColor="white"
          caroselImageStyle={{ height }}
          indicatorContainerStyle={{ bottom: -40 }}
          activeIndicatorStyle={styles.activeDot}
          inActiveIndicatorStyle={styles.inActiveDot}
        />
      </View>
    );
  };
  const renderInfo = () => {
    const tags = detail.tag?.map((i) => `# ${i}`).join(" ");
    return (
      <>
        <Text style={styles.articleTitleTxt}>{detail.title}</Text>
        <Text style={styles.descTxt}>{detail.desc}</Text>
        <Text style={styles.tagsTxt}>{tags}</Text>
        <Text style={styles.timeAndLocationTxt}>
          {detail.dateTime} {detail.location}
        </Text>
        <View style={styles.line} />
      </>
    );
  };
  const renderComments = () => {
    const count = detail.comments?.length || 0;
    const styles = StyleSheet.create({
      commentsCountTxt: {
        fontSize: 14,
        color: "#666",
        marginTop: 20,
        marginLeft: 16,
      },
      inputLayout: {
        width: "100%",
        padding: 16,
        flexDirection: "row",
        alignItems: "center",
      },
      userAvatarImg: {
        width: 32,
        height: 32,
        borderRadius: 16,
        resizeMode: "cover",
      },
      commentInput: {
        flex: 1,
        height: 40,
        borderRadius: 16,
        marginLeft: 12,
        backgroundColor: "#f0f0f0",
        color: "#333",
        paddingVertical: 4,
        paddingHorizontal: 12,
      },
      commentsContainer: {
        paddingHorizontal: 16,
        paddingTop: 16,
        paddingBottom: 32,
      },
      commentItem: {
        width: "100%",
        flexDirection: "row",
      },
      cAvatar: {
        width: 36,
        height: 36,
        resizeMode: "cover",
        borderRadius: 18,
      },
      contentLayout: {
        flex: 1,
        marginHorizontal: 12,
      },
      nameTxt: {
        fontSize: 12,
        color: "#999",
      },
      messageTxt: {
        fontSize: 14,
        color: "#333",
        marginTop: 6,
      },
      timeLocationTxt: {
        fontSize: 12,
        color: "#bbb",
      },
      countLayout: {
        alignItems: "center",
      },
      fCount: {
        fontSize: 12,
        color: "#666",
        marginTop: 2,
      },
      divider: {
        marginLeft: 50,
        marginRight: 0,
        height: StyleSheet.hairlineWidth,
        backgroundColor: "#eee",
        marginVertical: 16,
      },
    });
    return (
      <>
        <Text style={styles.commentsCountTxt}>
          {count ? `共 ${count} 条评论` : "暂无评论"}
        </Text>
        <View style={styles.inputLayout}>
          <Image
            style={styles.userAvatarImg}
            source={{ uri: userInfo.avatar }}
          />
          <TextInput
            style={styles.commentInput}
            placeholder="说点什么吧，万一火了呢～"
            placeholderTextColor={"#bbb"}
          />
        </View>
        {!!count && (
          <View style={styles.commentsContainer}>
            {detail.comments?.map((i: ArticleComment, index: number) => {
              return (
                <View key={`${index}`} style={{}}>
                  <View style={styles.commentItem}>
                    <Image
                      style={styles.cAvatar}
                      source={{ uri: i.avatarUrl }}
                    />
                    <View style={styles.contentLayout}>
                      <Text style={styles.nameTxt}>{i.userName}</Text>
                      <Text style={styles.messageTxt}>
                        {i.message}
                        <Text style={styles.timeLocationTxt}>
                          {dayjs(i.dateTime).format("MM-DD")} {i.location}
                        </Text>
                      </Text>
                      {!!i.children?.length &&
                        i.children.map(
                          (j: ArticleComment, subIndex: number) => {
                            return (
                              <View
                                key={`${index}-${subIndex}`}
                                style={[
                                  styles.commentItem,
                                  { marginTop: 12, width: SCREEN_WIDTH - 80 },
                                ]}
                              >
                                <Image
                                  style={[
                                    styles.cAvatar,
                                    { width: 32, height: 32 },
                                  ]}
                                  source={{ uri: j.avatarUrl }}
                                />
                                <View style={styles.contentLayout}>
                                  <Text style={styles.nameTxt}>
                                    {j.userName}
                                  </Text>
                                  <Text style={styles.messageTxt}>
                                    {j.message}
                                    <Text style={styles.timeLocationTxt}>
                                      {dayjs(j.dateTime).format("MM-DD")}{" "}
                                      {j.location}
                                    </Text>
                                  </Text>
                                </View>
                                <View style={styles.countLayout}>
                                  <Heart size={20} value={j.isFavorite} />
                                  <Text style={styles.fCount}>
                                    {j.favoriteCount}
                                  </Text>
                                </View>
                              </View>
                            );
                          }
                        )}
                    </View>
                    <View style={styles.countLayout}>
                      <Heart size={20} value={i.isFavorite} />
                      <Text style={styles.fCount}>{i.favoriteCount}</Text>
                    </View>
                  </View>
                  <View style={styles.divider} />
                </View>
              );
            })}
          </View>
        )}
      </>
    );
  };
  const renderBottom = () => {
    return (
      <View style={styles.bottomLayout}>
        <View style={styles.bottomEditLayout}>
          <AntDesign name="edit" size={20} color="#333" />
          <TextInput
            style={styles.bottomCommentInput}
            placeholder="说点什么"
            placeholderTextColor={"#333"}
          />
        </View>
        <Heart size={22} value={detail.isFavorite} color="grey" />
        <Text style={styles.bottomCount}>{detail.favoriteCount}</Text>
        <AntDesign name="staro" size={22} color="grey" />
        <Text style={styles.bottomCount}>{detail.collectionCount}</Text>
        <AntDesign name="message1" size={22} color="grey" />
        <Text style={styles.bottomCount}>{detail.comments?.length || 0}</Text>
      </View>
    );
  };
  return (
    <View style={styles.page}>
      <View style={styles.topBar}>
        <TouchableOpacity
          onPress={() => {
            router.back();
          }}
        >
          <Entypo name="chevron-left" size={24} color="black" />
        </TouchableOpacity>
        <Image style={styles.avatarImg} source={{ uri: detail.avatarUrl }} />
        <Text style={styles.nameTxt}>{detail.userName}</Text>
        <TouchableOpacity
          onPress={() => {
            console.log("关注");
          }}
        >
          <Text style={styles.followBtn}>关注</Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={() => {
            console.log("转发");
          }}
        >
          <EvilIcons
            style={styles.shareIcon}
            name="external-link"
            size={32}
            color="black"
          />
        </TouchableOpacity>
      </View>
      <ScrollView showsVerticalScrollIndicator={false}>
        {renderImages()}
        {renderInfo()}
        {renderComments()}
      </ScrollView>
      {renderBottom()}
    </View>
  );
}
const styles = StyleSheet.create({
  page: {
    backgroundColor: "white",
    width: "100%",
    height: "100%",
  },
  bottomLayout: {
    width: "100%",
    height: 64,
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 16,
    borderTopWidth: 1,
    borderTopColor: "#eee",
  },
  bottomEditLayout: {
    height: 40,
    flex: 1,
    backgroundColor: "#f0f0f0",
    borderRadius: 20,
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 12,
    marginRight: 12,
  },
  bottomCommentInput: {
    height: "100%",
    paddingTop: 6,
    paddingLeft: 6,
    color: "#333",
    textAlignVertical: "center",
    paddingVertical: 0,
  },
  bottomCount: {
    fontSize: 14,
    color: "grey",
    marginLeft: 6,
    marginRight: 8,
  },
  shareIcon: {
    marginBottom: 4,
  },
  articleTitleTxt: {
    fontSize: 18,
    color: "#333",
    fontWeight: "bold",
    paddingHorizontal: 16,
  },
  descTxt: {
    fontSize: 15,
    color: "#333",
    marginTop: 6,
    paddingHorizontal: 16,
  },
  tagsTxt: {
    fontSize: 15,
    color: "#305090",
    marginTop: 6,
    paddingHorizontal: 16,
  },
  timeAndLocationTxt: {
    fontSize: 12,
    color: "#bbb",
    marginVertical: 16,
    marginLeft: 16,
  },
  line: {
    marginHorizontal: 16,
    height: StyleSheet.hairlineWidth,
    backgroundColor: "#eee",
  },
  topBar: {
    flexDirection: "row",
    alignItems: "center",
    padding: 10,
  },
  avatarImg: {
    width: 30,
    height: 30,
    resizeMode: "cover",
    borderRadius: 50,
    margin: 10,
  },
  nameTxt: {
    fontSize: 14,
    color: "#999",
    marginLeft: 6,
    flex: 1,
  },
  followBtn: {
    fontSize: 12,
    color: "red",
    borderWidth: 1,
    borderColor: "red",
    borderRadius: 10,
    paddingVertical: 4,
    paddingHorizontal: 12,
    marginRight: 10,
  },
  activeDot: {
    width: 6,
    height: 6,
    backgroundColor: "#ff2442",
    borderRadius: 3,
  },
  inActiveDot: {
    width: 6,
    height: 6,
    backgroundColor: "#c0c0c0",
    borderRadius: 3,
  },
});
